/**
 * 项目资源使用统计数据状态Store
 */
import { observable, action, runInAction } from 'mobx-miniprogram';
import StatisticsRepository from '../../../services/statistics_repository';
import dayjs from 'dayjs';
import { standardizeModuleStore } from '../../helpers/store_standardizer';

const resourcesStore = observable({
  // 状态数据
  isLoading: false,
  hasError: false,
  errorMessage: '',
  
  // 统计数据
  teamSize: 0,
  plannedWorkload: 0,
  actualWorkload: 0,
  usageRate: 0,
  
  // 工时数据
  workloadData: [],
  workloadTableData: [],
  
  // 成本数据
  costData: [],
  costTableData: [],
  
  // 角色分布数据
  roleData: [],
  roleTableData: [],
  
  // 部门分布数据
  departmentData: [],
  departmentTableData: [],
  
  // 状态标志
  isDataLoaded: false,
  
  // 周期
  period: 'month',
  
  // 获取资源使用统计数据
  fetchResourcesData: action(async function(params = {}) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.hasError = false;
        this.errorMessage = '';
      });
      
      const { projectId, period = this.period } = params;
      
      if (!projectId) {
        throw new Error('项目ID不能为空');
      }
      
      // 设置period
      this.period = period;
      
      // 调用仓储层获取数据
      const result = await StatisticsRepository.getProjectResources(projectId, { period });
      
      // 处理返回的数据
      runInAction(() => {
        if (result && result.resources) {
          const resources = result.resources;
          
          // 设置团队规模和工作量数据
          this.teamSize = resources.teamSize || 0;
          this.plannedWorkload = resources.workload?.planned || 0;
          this.actualWorkload = resources.workload?.actual || 0;
          this.usageRate = this._calculateUsageRate(
            resources.workload?.planned,
            resources.workload?.actual
          );
          
          // 处理工时数据
          this.workloadData = this._processWorkloadData(resources.workloadTimeline || []);
          this.workloadTableData = this._processWorkloadTableData(resources.workloadTimeline || []);
          
          // 处理成本数据
          this.costData = this._processCostData(resources.costTimeline || []);
          this.costTableData = this._processCostTableData(resources.costTimeline || []);
          
          // 处理角色分布数据
          this.roleData = this._processRoleData(resources.teamDistribution || []);
          this.roleTableData = this._processRoleTableData(resources.teamDistribution || []);
          
          // 处理部门分布数据
          this.departmentData = this._processDepartmentData(resources.departmentDistribution || []);
          this.departmentTableData = this._processDepartmentTableData(resources.departmentDistribution || []);
          
          this.isDataLoaded = true;
        } else {
          this._resetData();
        }
        
        this.isLoading = false;
      });
      
      return result;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.hasError = true;
        this.errorMessage = error.message || '获取资源统计数据失败';
        this._resetData();
      });
      
      throw error;
    }
  }),
  
  // 重置数据
  _resetData: action(function() {
    this.teamSize = 0;
    this.plannedWorkload = 0;
    this.actualWorkload = 0;
    this.usageRate = 0;
    this.workloadData = [];
    this.workloadTableData = [];
    this.costData = [];
    this.costTableData = [];
    this.roleData = [];
    this.roleTableData = [];
    this.departmentData = [];
    this.departmentTableData = [];
    this.isDataLoaded = false;
  }),
  
  // 计算使用率
  _calculateUsageRate(planned, actual) {
    if (!planned || planned <= 0) return 0;
    const rate = (actual / planned) * 100;
    return parseFloat(rate.toFixed(2));
  },
  
  // 处理工时数据
  _processWorkloadData(timeline) {
    if (!timeline || !Array.isArray(timeline) || timeline.length === 0) {
      return [];
    }
    
    return timeline.map(item => ({
      name: this._formatTimelineLabel(item.date),
      date: item.date,
      planned: item.planned || 0,
      actual: item.actual || 0,
      remaining: item.remaining || 0
    }));
  },
  
  // 处理工时表格数据
  _processWorkloadTableData(timeline) {
    if (!timeline || !Array.isArray(timeline) || timeline.length === 0) {
      return [];
    }
    
    return timeline.map(item => ({
      date: this._formatTimelineLabel(item.date),
      planned: item.planned || 0,
      actual: item.actual || 0,
      remaining: item.remaining || 0,
      rate: this._calculateUsageRate(item.planned, item.actual)
    }));
  },
  
  // 处理成本数据
  _processCostData(timeline) {
    if (!timeline || !Array.isArray(timeline) || timeline.length === 0) {
      return [];
    }
    
    return timeline.map(item => ({
      name: this._formatTimelineLabel(item.date),
      date: item.date,
      planned: item.planned || 0,
      actual: item.actual || 0,
      remaining: item.remaining || 0
    }));
  },
  
  // 处理成本表格数据
  _processCostTableData(timeline) {
    if (!timeline || !Array.isArray(timeline) || timeline.length === 0) {
      return [];
    }
    
    return timeline.map(item => ({
      date: this._formatTimelineLabel(item.date),
      planned: item.planned || 0,
      actual: item.actual || 0,
      remaining: item.remaining || 0,
      rate: this._calculateUsageRate(item.planned, item.actual)
    }));
  },
  
  // 处理角色分布数据
  _processRoleData(distribution) {
    if (!distribution || !Array.isArray(distribution) || distribution.length === 0) {
      return [];
    }
    
    return distribution.map(item => ({
      name: item.role || '未知角色',
      count: item.count || 0,
      percentage: item.percentage || 0
    }));
  },
  
  // 处理角色表格数据
  _processRoleTableData(distribution) {
    if (!distribution || !Array.isArray(distribution) || distribution.length === 0) {
      return [];
    }
    
    return distribution.map(item => ({
      role: item.role || '未知角色',
      count: item.count || 0,
      percentage: item.percentage || 0,
      workload: item.workload || 0
    }));
  },
  
  // 处理部门分布数据
  _processDepartmentData(distribution) {
    if (!distribution || !Array.isArray(distribution) || distribution.length === 0) {
      return [];
    }
    
    return distribution.map(item => ({
      name: item.department || '未知部门',
      count: item.count || 0,
      percentage: item.percentage || 0
    }));
  },
  
  // 处理部门表格数据
  _processDepartmentTableData(distribution) {
    if (!distribution || !Array.isArray(distribution) || distribution.length === 0) {
      return [];
    }
    
    return distribution.map(item => ({
      department: item.department || '未知部门',
      count: item.count || 0,
      percentage: item.percentage || 0,
      workload: item.workload || 0
    }));
  },
  
  // 格式化时间轴标签
  _formatTimelineLabel(date) {
    if (!date) return '未知';
    
    // 根据周期格式化日期
    switch(this.period) {
      case 'week':
        return dayjs(date).format('MM-DD');
      case 'month':
        return dayjs(date).format('MM-DD');
      case 'quarter':
        return dayjs(date).format('MM月');
      case 'year':
        return dayjs(date).format('YY年Q季度');
      default:
        return dayjs(date).format('YY-MM-DD');
    }
  },
  
  // 切换周期
  changePeriod: action(function(period) {
    if (['week', 'month', 'quarter', 'year', 'all'].includes(period)) {
      this.period = period;
    }
  }),
  
  // 重置Store
  resetStore: action(function() {
    this.isLoading = false;
    this.hasError = false;
    this.errorMessage = '';
    this.period = 'month';
    this._resetData();
  })
});

// 标准化模块Store
export const standardizedStore = standardizeModuleStore(resourcesStore);

// 导出
export { resourcesStore }; 